package cn.edu.jxau.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Desc: 面向.properties文件的一个工具类
 * ------------------------------------
 * Author:fulei04@meituan.com
 * Date:2017/12/14
 * Time:上午8:27
 */
public class PropUtils {

    public static Properties load(String path) {

        if (!path.endsWith(".properties")) {
            throw new IllegalArgumentException("无法读取除.properties类型以外的文件");
        }
        try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);) {
            if (in == null) {
                throw new IOException("路径错误，无法读取.properties文件");
            }
            Properties prop = new Properties();
            prop.load(in);
            return prop;
        } catch (IOException e) {
            throw new RuntimeException(".properties文件读取失败",e);
        }
    }

    public static String getString(Properties prop,String key,String defaulVal) {
        return prop.getProperty(key) == null ? defaulVal :  prop.getProperty(key);
    }

    public static String getString(Properties prop,String key) {
        return getString(prop,key,"");
    }

    public static Integer getInt(Properties prop,String key,Integer defaultVal) {

        String val = prop.getProperty(key);
        return val == null ? defaultVal : Integer.parseInt(val);
    }

    public static Integer getInt(Properties prop,String key) {
        return getInt(prop,key,0);
    }

    public static boolean getBoolean(Properties prop,String key,boolean defaultVal) {

        String val = prop.getProperty(key);
        return val == null ? defaultVal : Boolean.parseBoolean(val);
    }

    public static boolean getBoolean(Properties prop,String key) {
        return getBoolean(prop,key);
    }

}
